package org.wdj.controller;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.wdj.pojo.Result;
import org.wdj.pojo.User;
import org.wdj.service.UserService;
import org.wdj.utils.EmailUtil;
import org.wdj.utils.JwtUtil;
import org.wdj.utils.Md5Util;
import org.wdj.utils.ThreadLocalUtil;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$") String password){

            User user = userService.findByUsername(username);
            if(user == null){
                userService.register(username,password);
                return Result.success();
            }
            else{
                return Result.error("用户名已存在");
            }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_-]{5,16}$") String password){
        User loginUser = userService.findByUsername(username);
        if(loginUser == null){
            return Result.error("用户名错误或不存在");
        }
        else{
            if(Md5Util.checkPassword(password,loginUser.getPassword())){
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", loginUser.getId());
                claims.put("username", loginUser.getUsername());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }
        }

        return Result.error("密码错误");
    }
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token */){
       /* Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String)map.get("username");*/
        Map<String, Object> map  = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUsername(username);

        return Result.success(user);
    }
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params){
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User loginUser = userService.findByUsername(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }

        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }

        userService.updatePwd(newPwd);
        return Result.success();
    }
    String SendCode = "";
    @PostMapping("/send")
    public Result send(@RequestParam("email") String email){
        User user = userService.findByUserEmail(email);
        if(user == null){
            return Result.error("邮箱不存在");
        }
        else{
            SendCode = String.valueOf((int)(Math.random()*10000));
            EmailUtil.send(user.getEmail(), user.getUsername(), SendCode);
        }
        return Result.success();
    }

    @PostMapping("/reset")
    public Result reset(@RequestParam("email") String email, @RequestParam("code") String code, @RequestParam("newPassword") String newPwd, @RequestParam("confirmPassword") String rePwd){
        User user = userService.findByUserEmail(email);

        if(SendCode == null || !SendCode.equals(code)){
            return Result.error("输入验证码错误");
        }
        else{
            if(!newPwd.equals(rePwd)){
                return Result.error("两次密码不一致");
            }
            userService.updatePwdByEmail(newPwd, user.getId());
        }
        SendCode = null;
        return Result.success();
    }

}
